package settings;

import java.io.*;
import java.util.*;

public abstract class Settings {

    public static final String PACKAGE_NAME = Settings.class.getName().replaceFirst("\\.\\w*?$", "");
    public static final String SETTINGS_DIR = System.getProperty("ms.confDir", PACKAGE_NAME.replace('.', '/') + "/../..");
    private static final String DEFAULTS = SETTINGS_DIR + "/default.properties";
    private static Properties properties;

    private static synchronized void load() {

        //loading default settings from .properties file
        properties = new Properties();
        try {
            System.out.println("DEFAULTS: " + DEFAULTS);
            InputStream is = Thread.currentThread().getContextClassLoader().getResource(DEFAULTS).openStream();
            try {
                properties.load(is);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            System.out.println(e);
            throw new RuntimeException(e);
        }
        System.out.println("loading default SETTING from: "+DEFAULTS+" size: "+properties.size());
    }

    protected static Properties getProperties() {
        if (properties == null) {
            synchronized (Settings.class) {
                if (properties == null) {
                    load();
                }
            }
        }
        return properties;
    }

    public static String getString(String key) {
        String value = getProperties().getProperty(key);
        // log.debug("getting string parameter \"{}\" ({})", key, value);
        return value;
    }

    public static int getInt(String key) {
        String value = getProperties().getProperty(key);
        // log.debug("getting int parameter \"{}\" ({})", key, value);
        return value.length() != 0 ? Integer.parseInt(value) : 0;
    }

    public static float getFloat(String key) {
        String value = getProperties().getProperty(key);
        // log.debug("getting float parameter \"{}\" ({})", key, value);
        return value.length() != 0 ? Float.parseFloat(value) : 0f;
    }
}
